package com.itrip.service.impl;

import com.itrip.service.SendMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * 邮件验证服务
 */
@Service
@Slf4j
public class SendMailServiceImpl implements SendMailService {
    @Value("${email.account}")
    private String account;
    @Value("${email.password}")
    private String password;
    @Value("${email.host}")
    private String host;

    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean sendEmail(String email, String code, int minute) {

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(account, password); //发件人邮件用户名、授权码
            }
        });

        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(account));
            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(email));
            // Set Subject: 头部头字段
            message.setSubject("【i旅行】请激活您的账号");
            String template = "<h1>请点击<a href='http://itrip.test.com/auth/api/web-activate?user=email&Code=code'>链接</a>激活您的账户</h1>";
            // 设置消息体
            String html = template.replace("email",email)
                    .replace("code",code);
            message.setContent(html,"text/html; charset=utf-8");
            // 发送消息
            Transport.send(message);
            log.debug("发送邮件成功" + html);
            redisTemplate.opsForValue().set(email,code,minute, TimeUnit.MINUTES);
            return true;
        }catch (MessagingException mex) {
            mex.printStackTrace();
            log.error("发送邮件给{}失败",email);
        }
        return false;
    }

    @Override
    public boolean validate(String email, String code) {
         //先获取到redis中的code
        String redisCode = (String)redisTemplate.opsForValue().get(email);
        if(redisCode!=null && redisCode.equals(code)){
              //说明是存在的
             redisTemplate.delete(email);
             return true;
        }
        //否则不存在
        return false;
    }
}
